<script setup>
import GoBackAndSearchNav from "@/components/GoBackAndSearchNav.vue";
import {ref, onBeforeMount, watchEffect} from "vue";
import {getCommentById, getProductById} from "@/api/product.js";
import {useRoute, useRouter} from 'vue-router'
import ProductImgSwipe from "@/views/product/components/ProductImgSwipe.vue";
import ProductPriceTitleSale from "@/views/product/components/ProductPriceTitleSale.vue";
import {findProductOptionMinPrice} from "@/utils/XwbUtils.js";
import ProductDelivery from "@/views/product/components/ProductDelivery.vue";
import ProductParams from "@/views/product/components/ProductParams.vue";
import ProductLabel from "@/views/product/components/ProductLabel.vue";
import ProductRecommond from "@/views/product/components/ProductRecommond.vue";
import TailPrice from "@/components/TailPrice.vue";
import {showImagePreview} from "vant";
import 'vant/es/image-preview/style'
import ProductDataNull from "@/views/product/components/ProductDataNull.vue";
import {addCarAPI} from "@/api/car.js";
import {CAR_ROUTE} from "@/router/routes/car/car.js";
import useAccountStore from "@/store/modules/AccountStore.js";
import {LOGIN_ROUTE} from "@/router/routes/login/login.js";
import {loginEffectiveAPI} from "@/api/login.js";
import {ORDER_ROUTE} from "@/router/routes/order/order.js";
import useOrderStore from "@/store/modules/OrderStore.js";
import Null from "@/components/Null.vue";
import ProductComment from "@/views/product/components/ProductComment.vue";

const route = useRoute()
const router = useRouter()

// 标签页
const tabMaxCnt = 4
const tabActive = ref(0)

// 手势事件处理
const swipeLeft = () => {
  if (tabActive.value < tabMaxCnt - 1) {
    tabActive.value += 1
  }
}
const swipeRight = () => {
  if (tabActive.value > 0) {
    tabActive.value -= 1
  }
}

// 初始化数据
const product = ref({})
const minPrice = ref(0)
// 当前选中的商品图片、商品选项名称、商品选项价格
const productImgSelected = ref('')
const productOptionNameSelected = ref('')
const productOptionPriceSelected = ref(0)
const productOptionIdx = ref(0)
const productOptionCntMax = ref(1)
const btnDisable = ref(false)
const commentList = ref([])
const getComment = async () => {
  commentList.value = await getCommentById(product.value.id)
}
onBeforeMount(async () => {
  const productId = route.query.productId
  // 获取商品信息
  product.value = await getProductById(productId)
  // 商品最小价格
  minPrice.value = findProductOptionMinPrice(product.value.options)
  let idx = 0;
  while (product.value?.options[idx].stock <= 0 && idx < product.value?.options.length - 1) {
    idx++;
    productOptionIdx.value = idx;
  }
  let optionCanSelectCnt = 0
  for (let i = 0; i < product.value?.options.length; i++) {
    if (product.value?.options[idx].stock > 0) optionCanSelectCnt++
  }
  if (optionCanSelectCnt === 0) btnDisable.value = true
  productImgSelected.value = product.value?.options[idx].img
  productOptionNameSelected.value = product?.value.options[idx].name
  productOptionPriceSelected.value = product?.value.options[idx].price
  productOptionCntMax.value = product?.value.options[idx].stock
  await getComment()
})

// 商品选项
const floatPanelVisible = ref(false)
const isPayNow = ref(false)
const anchors = ref([window.innerHeight * 0.85])
const onOpenPanel = async (payNow) => {
  const accountStore = useAccountStore()
  // account
  const account = accountStore.account
  // 未登录过
  if (account === null || account === undefined || account.length <= 0) {
    // 前往登录
    router.push({name: LOGIN_ROUTE})
    return
  }
  // 登录过，校验登录是否还有效
  let res = await loginEffectiveAPI()
  // 登录无效，前往登录
  if (!res) {
    router.push({name: LOGIN_ROUTE})
    return
  }
  floatPanelVisible.value = true
  isPayNow.value = payNow
}
const onClosePanel = () => {
  floatPanelVisible.value = false
}

// 商品选项选择个数
const productOptionCnt = ref(1)
// 商品选项选择
const selectProductOption = (option, idx) => {
  if (option.stock <= 0) return
  productImgSelected.value = option?.img
  productOptionNameSelected.value = option?.name
  productOptionPriceSelected.value = option?.price
  productOptionIdx.value = idx
  productOptionCnt.value = 1
  productOptionCntMax.value = option.stock
};
// 商品选项图片预览
const productOptionImgPreview = () => {
  showImagePreview([productImgSelected.value]);
}

// 加入购物车
const addCar = async () => {
  const res = await addCarAPI(product.value.id, product.value.options[productOptionIdx.value].id, productOptionCnt.value)
  if (res) {
    onClosePanel()
  }
}

const goCar = () => {
  router.push({name: CAR_ROUTE})
}

// 立即购买
const payNow = async () => {
  // 构建订单信息
  const orderProduct = {
    id: null, // 购物车 id
    title: product.value.title, // 商品标题
    freight: product.value.freight, // 运费
    name: product.value.options[productOptionIdx.value].name,
    img: product.value.options[productOptionIdx.value].img,
    num: productOptionCnt.value, // 商品数量
    price: productOptionPriceSelected.value, // 商品价格
    productId: product.value.id,
    productOptionId: product.value.options[productOptionIdx.value].id,
    stock: product.value.options[productOptionIdx.value].stock,
    userId: useAccountStore().user.id,
  }
  // 添加 store
  useOrderStore().saveProducts([orderProduct])
  // 前往订单页面
  router.push({name: ORDER_ROUTE})
}
</script>

<template>
  <div class="product min-h-screen" v-touch:swipe.left="swipeLeft" v-touch:swipe.right="swipeRight">
    <GoBackAndSearchNav :title="''" :placeholder="true"></GoBackAndSearchNav>
    <van-tabs class="z-0" v-model:active="tabActive">
      <van-tab title="商品">
        <ProductImgSwipe :imgs="product?.imgs?.map(i => i.img)"></ProductImgSwipe>
        <div class="pb-2">
          <ProductPriceTitleSale
              :price="minPrice"
              :title="product?.title"
              :sale="product?.sale"
          ></ProductPriceTitleSale>
          <ProductDelivery
              :delivery="product.delivery"
              :address="product.address"
          ></ProductDelivery>
          <ProductLabel :labels="product.labels"></ProductLabel>
          <ProductParams
              :isbn="product.code"
              :params="product.params"
          ></ProductParams>
        </div>
      </van-tab>
      <van-tab class="product-detail" title="详情">
        <div
            v-if="product?.descriptionHtml?.length > 0"
            class="product-detail-content m-2 p-2 rounded-lg overflow-hidden bg-white dark:bg-neutral-900 dark:text-gray-100"
            v-html="product?.descriptionHtml"
        ></div>
        <ProductDataNull
            v-else
            :title="'暂无商品详情...'"
            :go-back-btn-visible="false"
        ></ProductDataNull>
      </van-tab>
      <van-tab title="评论">
        <Null v-if="commentList.length <= 0"></Null>
        <ProductComment
            v-for="item in commentList"
            :comment="item"
        ></ProductComment>
      </van-tab>
      <van-tab title="推荐">
        <ProductRecommond
            :category-id="product?.productCategoryId"
            :category-sub-id="product?.productCategorySubId"
        ></ProductRecommond>
      </van-tab>
    </van-tabs>
    <van-action-bar placeholder>
      <!--<van-action-bar-icon icon="chat-o" text="客服" color="#ee0a24"/>-->
      <van-action-bar-icon icon="cart-o" text="购物车" @click="goCar"/>
      <!--<van-action-bar-icon icon="star" text="已收藏" color="#ff5000"/>-->
      <van-action-bar-button @click="onOpenPanel(false)" type="warning" text="加入购物车"/>
      <van-action-bar-button @click="onOpenPanel(true)" type="danger" text="立即购买"/>
    </van-action-bar>
    <van-overlay :show="floatPanelVisible" @click="onClosePanel" lock-scroll>
      <div class="flex-start-center pl-4 pr-4 pt-4">
        <div class="img w-16 h-16 mr-2 flex-nowrap">
          <img class="w-full h-full object-contain"
               :src="productImgSelected" alt=""
               @click.stop="productOptionImgPreview"
          >
        </div>
        <div class="name text-sm text-gray-100 w-5/6">
          {{ productOptionNameSelected }}
        </div>
      </div>
    </van-overlay>
    <van-floating-panel
        :content-draggable="true"
        :anchors="anchors"
        v-show="floatPanelVisible"
    >
      <div class="h-full flex flex-col justify-between">
        <div class="p-2">
          <div class="flex justify-between items-center">
            <TailPrice
                :price="productOptionPriceSelected.toString()"
                :isStart="false"
            ></TailPrice>
            <div class="mr-4 text-neutral-600 dark:text-gray-200" @click="onClosePanel">
              <span class="iconfont icon-close"></span>
            </div>
          </div>
          <div
              v-for="(item, idx) in product?.options"
              @click="selectProductOption(item, idx)"
              class="product-option bg-gray-50 dark:bg-neutral-950 dark:text-gray-100 mt-2 p-2 rounded-xl overflow-hidden flex justify-between items-center"
              :class="[productOptionIdx === idx ? 'product-option-selected' : '', item?.stock <= 0 ? 'text-gray-300' : '']"
          >
            <div class="flex-start-center">
              <div class="img w-12 h-12 mr-2">
                <img class="w-full h-full object-contain" :src="item.img" alt="">
              </div>
              <div class="name text-sm w-52">
                {{ item?.name }}
              </div>
            </div>
            <div class="price text-sm flex-nowrap">￥ {{ item?.price }}</div>
          </div>
          <div class="mt-4 flex justify-between items-center">
            <span>数量</span>
            <van-stepper
                v-model="productOptionCnt"
                integer
                :min="1"
                :max="productOptionCntMax"
                theme="round"
                button-size="22"
            />
          </div>
        </div>
        <div class="p-4">
          <van-button v-if="!isPayNow"
                      color="linear-gradient(to right, #ffb41b, #ff5f34)"
                      round block
                      :disabled="btnDisable"
                      @click="addCar"
          >
            加入购物车
          </van-button>
          <van-button v-else
                      color="linear-gradient(to right, #ff8a17, #ee0a24)"
                      round
                      :disabled="btnDisable"
                      block
                      @click="payNow"
          >
            立即购买
          </van-button>
        </div>
      </div>
    </van-floating-panel>
  </div>
</template>

<style lang="scss">
.product-option {
  border: 1px solid transparent;
  font-weight: 300;
}

.product-option-selected {
  border: 1px solid #ff5000;
}

.product-detail-content {
  max-width: 100%;
  overflow: auto;

  h1 {
    font-size: 24px;
    font-weight: 600;
    line-height: 32px;
    margin-bottom: 16px;
  }

  h2 {
    font-size: 20px;
    font-weight: 600;
    line-height: 28px;
    margin-bottom: 16px;
  }

  h3 {
    font-size: 16px;
    font-weight: 600;
    line-height: 24px;
    margin-bottom: 16px;
  }

  h4 {
    font-size: 14px;
    font-weight: 600;
    line-height: 20px;
    margin-bottom: 16px;
  }

  p {
    font-size: 14px;
    line-height: 24px;
    margin-bottom: 16px;
  }
}
</style>